import {
    forwardRef, useEffect, useImperativeHandle, useRef, useState,
} from 'react';
import { Spin } from 'antd';
import Modal from '@/components/Modal';
import ProForm, { type formConfigProps } from '@/components/ProForm';
import { goodsInfo, goodsGameAttr } from '@/api/modules/goods';

import "./index.less";

const fieldNames = { label: 'name', value: 'id', groupLabel: 'name' };

const Comp = forwardRef((props: any, ref: any) => {
    const formRef = useRef(props);
    const [modalObj, setModalObj] = useState({
        width: '1200px',
        title: '录入回收单信息',
        open: false,
        loading: false,
        confirmLoading: false,
        id: undefined,
        game_id: undefined,
    });
    const [formConfig, setFormConfig] = useState<formConfigProps[]>([]);
    const [optionsMap, setOptionsMap] = useState({
        tagRes: {},
        transacionRes: {},
        channelRes: {},
        allGameRes: {},
        allUserRes: {},
    });

    const getFormConfig = (
        { tagRes, transacionRes, channelRes, allGameRes, allUserRes }: any,
        detail: any,
        dyncData: any,
    ):formConfigProps[] => {
        const { cover, image_url, goodsAttr } = detail;
        console.log(tagRes, transacionRes, channelRes, allGameRes, allUserRes, '123');
        const newServer = detail.server || {};
        const isMultiple = dyncData.filter((item: any) => item.is_multiple === 1);
        const isNoMultiple = dyncData.filter((item: any) => item.is_multiple !== 1);
        const newCover = cover ? {
            uid: -100,
            name: -100,
            status: 'done',
            url: cover,
        } : undefined;
        const newImageUrl = (image_url || []).map((item: any, index: any) => ({
            uid: index,
            name: index,
            status: 'done',
            url: item,
        }));
        const newGoodsAttr = (goodsAttr || []).reduce((init: any, item: any) => ({
            ...init,
            [item.group_id]: `${item.group_id}_${item.attr_id}_${item.attr_name}`,
        }), {});
        const newServerOptions = ((allGameRes.data || []).find((item: any) => item.id === modalObj.game_id) || {}).server || [];
        const dyncData1 = isNoMultiple.reduce((iinit: any, iitem: any) => {
            if (iitem.is_no_attr === 2) {
                iinit.push({
                    name: ['preset_data', `attr@${iitem.id}`],
                    label: iitem.group_name,
                    valueType: 'select',
                    options: iitem.attribute || [],
                    span: 8,
                    formProps: {
                        fieldNames: { ...fieldNames, value: 'option_id' },
                        mode: iitem.is_multiple === 1 ? 'multiple' : undefined,
                    },
                    required: iitem.is_must,
                    initialValue: newGoodsAttr[iitem.id],
                });
            }
            if (iitem.is_no_attr === 1) {
                iinit.push({
                    name: ['preset_data', iitem.id],
                    label: iitem.group_name,
                    valueType: 'text',
                    span: 8,
                    required: iitem.is_must,
                    initialValue: newGoodsAttr[iitem.id],
                });
            }
            return iinit;
        }, []);
        const dyncData2 = isMultiple.reduce((iinit: any, iitem: any) => {
            const newAttribute = (iitem.attribute || []);
            const newValueType = (newAttribute[0] || {}).child ? 'checkboxChildren' : 'checkbox';
            const newDefaultV = (goodsAttr || []).filter((item: any) => item.group_id === iitem.id)
                .map((item: any) => `${item.group_id}_${item.attr_id}_${item.attr_name}`);
            console.log(newDefaultV, iitem.group_name, 121233)
            iinit.push({
                name: ['preset_data', `attr@${iitem.id}`],
                label: '',
                valueType: newValueType,
                span: 24,
                hr: iitem.group_name,
                options: (iitem.attribute || []).map((item: any) => ({
                    ...item,
                    label: item.name,
                    value: `${iitem.id}_${item.id}_${item.name}`,
                })),
                initialValue: newDefaultV,
            });
            return iinit;
        }, []);
        
        // const dyncData2 = isMultiple

        return [{
            title: '基础信息',
            description: '（火影忍者: HY00007）',
            span: 24,
            formList: [{
                name: 'title',
                label: '商品标题',
                valueType: 'textarea',
                formProps: { rows: 6 },
                span: 24,
                initialValue: detail.title,
            }, {
                name: 'account',
                label: '商品账号',
                valueType: 'text',
                span: 8,
                initialValue: detail.account,
            }, {
                name: 'password',
                label: '商品密码',
                valueType: 'text',
                span: 8,
                initialValue: detail.password,
            }, {
                name: 'level',
                label: '等级',
                valueType: 'text',
                required: true,
                span: 8,
                initialValue: detail.level,
            }, {
                name: 'price',
                label: '价格',
                valueType: 'text',
                required: true,
                span: 8,
                initialValue: detail.price,
            }, {
                name: 'recovery_sn',
                label: '游戏区服',
                valueType: 'cascader',
                required: true,
                span: 8,
                options: newServerOptions,
                formProps: { fieldNames },
                initialValue: newServer.pid ? [newServer.pid, newServer.id] : undefined,
            }, {
                name: 'description',
                label: '商品描述',
                valueType: 'textarea',
                formProps: { rows: 6 },
                required: true,
                span: 24,
                initialValue: detail.description,
            }, ...dyncData1],
        }, {
            title: '图片信息',
            span: 24,
            formList: [{
                name: 'cover',
                label: '主图(封面图)',
                initialValue: newCover,
                valueType: 'upload',
                formProps: { maxCount: 1 },
            }, {
                name: 'image_url',
                label: '其他游戏截图',
                initialValue: newImageUrl,
                valueType: 'upload',
            }]
        }, {
            title: '属性信息',
            span: 24,
            formList: dyncData2,
        }];
    }
    const onCancel = () => {
        setModalObj((pre) => ({ ...pre, open: false }));
    };
    const onOk = () => {
        formRef.current.validateFields().then(async (values: any) => {
            const {
                cover, image_url, // 图片只要url
                preset_data, // 动态表单数据重新组装
                ...other
            }: any = values;
            const postData = {
                ...other,
                // [1, 2, 3, [1, 2, 3]] 扁平化 数据里面还有数组
                attribute: JSON.stringify(
                    (Object.values(preset_data).filter((item: any) => item && item.length).reduce((init: any, item: any) => ([
                        ...init,
                        ...(Array.isArray(item) ? item : [item]),
                    ]), []) as any[]).join(',')
                ),
                cover: (cover || {}).url,
                image_url: (image_url || []).map((item: any) => item.url),
            };
            console.log(postData);
            try {
                setModalObj((pre) => ({ ...pre, loading: true, confirmLoading: true }));
                // const { data } = await addRecovery(values);
                setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
            } catch (err) {
                setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
            }
        })
    };
    const initData = async () => {
        try {
            const asyncArr = [];
            if (modalObj.id) asyncArr.push(goodsInfo({ id: modalObj.id  }));
            if (modalObj.game_id) asyncArr.push(goodsGameAttr({ game_id: modalObj.game_id  }));
            setModalObj((pre) => ({ ...pre, loading: true, confirmLoading: true }));
            const [infoRes, attrRes]: any = await Promise.all(asyncArr);
            const newDetail = (infoRes && infoRes.data) || {};
            const dyncData = (attrRes && attrRes.data) || [];
            setFormConfig(getFormConfig({ ...optionsMap }, newDetail, dyncData));
            setModalObj((pre) => ({
                ...pre,
                loading: false,
                confirmLoading: false,
                defail: newDetail,
            }));
        } catch (err) {
            console.log(err, '报错都会走这里！');
            setModalObj((pre) => ({ ...pre, loading: false, confirmLoading: false }));
        }
    };
    useImperativeHandle(ref, () => ({
        modalObj,
        show: () => setModalObj((pre) => ({ ...pre, open: true, id: undefined, detail: undefined })),
        showDetail: (id: any, game_id: any) => setModalObj((pre) => ({ ...pre, open: true, id, game_id })),
        setOptionsMap,
    }));

    useEffect(() => {
        if (modalObj.open === true) initData();
    }, [modalObj.open]);

	return (
        <>
            {
                modalObj.open ? (
                    <Modal
                        {...modalObj}
                        onOk={onOk}
                        onCancel={onCancel}
                        loading={false}
                    >
                        {
                            modalObj.loading ? <Spin spinning /> : <ProForm ref={formRef} formConfig={formConfig} />
                        }
                    </Modal>
                ) : ''
            }
        </>
	);
});

Comp.displayName = 'goods-form-modal';

export default Comp;
